﻿using M2Server.CommandSystem;
using NetFramework.AsyncSocketServer;
using System;
using System.Collections.Generic;
using System.IO;
using SystemModule;
using SystemModule.Thrend;

namespace M2Server
{
    public class GameServer
    {
        #region 变量区
        private ServerEngine serverEngine;
        private static IServerSocket GateSocket = null;
        private static bool boSaveData = false;
        private LocalDB FrmDB;

        #endregion 变量区

        public GameServer()
        {
            serverEngine = new ServerEngine();
        }

        public void Run()
        {
            StartGame();
        }

        /// <summary>
        /// 生成程序标题
        /// </summary>
        /// <param name="Msg"></param>
        /// <param name="nLen"></param>
        public void SetWindowTitle(string Msg)
        {
            M2Share.sCaptionExtText = Msg;
            Console.Title = M2Share.sCaptionExtText;
        }

        /// <summary>
        /// 加载文字过滤
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        private static bool LoadAbuseInformation(string FileName)
        {
            bool result = false;
            string sText;
            if (File.Exists(FileName))
            {
                M2Share.AbuseTextList.Clear();
                M2Share.AbuseTextList.LoadFromFile(FileName);
               var i = 0;
                while (true)
                {
                    if (M2Share.AbuseTextList.Count <= i)
                    {
                        break;
                    }
                    sText = M2Share.AbuseTextList[i].Trim();
                    if (sText == "")
                    {
                        M2Share.AbuseTextList.RemoveAt(i);
                        continue;// 继续
                    }
                    i++;
                }
                result = true;
            }
            return result;
        }

        // 读取服务器IP及端口
        private static void LoadServerTable()
        {
            TStringList LoadList;
            TStringList GateList;
            string sLineText = string.Empty;
            string sGateMsg = string.Empty;
            string sIPaddr = string.Empty;
            string sPort = string.Empty;
            if (M2Share.ServerTableList.Count > 0)
            {
                for (var i = 0; i < M2Share.ServerTableList.Count; i++)
                {
                    // ((M2Share.ServerTableList[i]) as ArrayList).Free;
                }
            }
            M2Share.ServerTableList.Clear();
            if (File.Exists(".\\!servertable.txt"))
            {
                LoadList = new TStringList();
                LoadList.LoadFromFile(".\\!servertable.txt");
                for (var i = 0; i < LoadList.Count; i++)
                {
                    sLineText = LoadList[i].Trim();
                    if ((sLineText != "") && (sLineText[0] != ';'))
                    {
                        sGateMsg = HUtil32.GetValidStr3(sLineText, ref sGateMsg, new string[] { " ", "\09" }).Trim();
                        if (sGateMsg != "")
                        {
                            GateList = new TStringList();
                            for (var k = 0; k <= 30; k++)
                            {
                                if (sGateMsg == "")
                                {
                                    break;
                                }
                                sGateMsg = HUtil32.GetValidStr3(sGateMsg, ref sIPaddr, new string[] { " ", "\09" }).Trim();
                                sGateMsg = HUtil32.GetValidStr3(sGateMsg, ref sPort, new string[] { " ", "\09" }).Trim();
                                if ((sIPaddr != "") && (sPort != ""))
                                {
                                    GateList.InsertText(HUtil32.Str_ToInt(sPort, 0), sIPaddr);
                                }
                            }
                            M2Share.ServerTableList.Add(GateList);
                            GateList = null;
                        }
                    }
                }
                LoadList = null;
                LoadList.Dispose();
            }
            else
            {
                Console.WriteLine("文件!servertable.txt未找到！！！");
            }
        }

        // 保存!Setup.txt内容
        private void SaveItemNumber()
        {
            try
            {
                //M2Share.ServerConfig.Config.WriteInteger("Setup", "ItemNumber", M2Share.g_Config.nItemNumber);
                //M2Share.ServerConfig.Config.WriteInteger("Setup", "ItemNumberEx", M2Share.g_Config.nItemNumberEx);
                //for (int i = M2Share.g_Config.GlobalVal.GetLowerBound(0); i <= M2Share.g_Config.GlobalVal.GetUpperBound(0); i++) // 保存系统变量
                //{
                //    M2Share.ServerConfig.Config.WriteInteger("Setup", "GlobalVal" + i, M2Share.g_Config.GlobalVal[i]);
                //}
                //for (int i = M2Share.g_Config.GlobalAVal.GetLowerBound(0); i <= M2Share.g_Config.GlobalAVal.GetUpperBound(0); i++)  // 保存系统变量
                //{
                //    M2Share.ServerConfig.Config.WriteString("Setup", "GlobalStrVal" + i, M2Share.g_Config.GlobalAVal[i]);
                //}
                //M2Share.ServerConfig.Config.WriteInteger("Setup", "WinLotteryCount", M2Share.g_Config.nWinLotteryCount);
                //M2Share.ServerConfig.Config.WriteInteger("Setup", "NoWinLotteryCount", M2Share.g_Config.nNoWinLotteryCount);
                //M2Share.ServerConfig.Config.WriteInteger("Setup", "WinLotteryLevel1", M2Share.g_Config.nWinLotteryLevel1);
                //M2Share.ServerConfig.Config.WriteInteger("Setup", "WinLotteryLevel2", M2Share.g_Config.nWinLotteryLevel2);
                //M2Share.ServerConfig.Config.WriteInteger("Setup", "WinLotteryLevel3", M2Share.g_Config.nWinLotteryLevel3);
                //M2Share.ServerConfig.Config.WriteInteger("Setup", "WinLotteryLevel4", M2Share.g_Config.nWinLotteryLevel4);
                //M2Share.ServerConfig.Config.WriteInteger("Setup", "WinLotteryLevel5", M2Share.g_Config.nWinLotteryLevel5);
                //M2Share.ServerConfig.Config.WriteInteger("Setup", "WinLotteryLevel6", M2Share.g_Config.nWinLotteryLevel6);
            }
            catch
            {
            }
        }

        private void RefreshData(object obj)
        {
            HUtil32.EnterCriticalSection(M2Share.LogMsgCriticalSection);
            try
            {
                if (M2Share.MainLogMsgList.Count > 0)
                {
                    try
                    {
                        if (M2Share.boStartReady)
                        {
                            for (int i = 0; i < M2Share.MainLogMsgList.Count; i++)
                            {
                                OutManMessage(M2Share.MainLogMsgList[i]);
                            }
                            M2Share.MainLogMsgList.Clear();
                        }
                    }
                    catch
                    {
                        OutManMessage("保存日志信息出错！！！");
                    }
                }
                if (M2Share.LogStringList.Count > 0)
                {
                    for (int i = 0; i < M2Share.LogStringList.Count; i++)
                    {
                        try
                        {
                            //sCaption = "1" + "\09" + M2Share.g_Config.nServerNumber + "\09" + M2Share.nServerIndex + "\09" + M2Share.LogStringList[i];
                            //IdUDPClientLog.Send(sCaption);// 发送游戏日志,文本内容
                        }
                        catch
                        {
                            continue;
                        }
                    }
                    M2Share.LogStringList.Clear();
                }
                M2Share.LogonCostLogList.Clear();
            }
            finally
            {
                HUtil32.LeaveCriticalSection(M2Share.LogMsgCriticalSection);
            }

            M2Share.dwStartTime = (HUtil32.GetTickCount() - M2Share.dwStartTimeTick) / 1000;
            M2Share.nRunTimeMax++;
            if (M2Share.g_nSockCountMax > 0) { M2Share.g_nSockCountMax -= 1; }
            if (M2Share.g_nUsrTimeMax > 0) { M2Share.g_nUsrTimeMax -= 1; }
            if (M2Share.g_nHumCountMax > 0) { M2Share.g_nHumCountMax -= 1; }
            if (M2Share.g_nMonTimeMax > 0) { M2Share.g_nMonTimeMax -= 1; }
            if (M2Share.dwUsrRotCountMax > 0) { M2Share.dwUsrRotCountMax -= 1; }
            if (M2Share.g_nMonGenTimeMin > 1) { M2Share.g_nMonGenTimeMin -= 2; }
            if (M2Share.g_nMonProcTimeMin > 1) { M2Share.g_nMonProcTimeMin -= 2; }
            if (M2Share.g_nBaseObjTimeMax > 0) { M2Share.g_nBaseObjTimeMax -= 1; }
        }

        /// <summary>
        /// 初始化引擎
        /// </summary>
        private void StartGame()
        {
            int nCode;
            StartService();
            FrmDB = LocalDB.GetInstance();
            try
            {
                if (!LoadClientFile())// 如果没有加载客户端信息
                {
                    Environment.Exit(Environment.ExitCode);
                    return;
                }
                M2Share.LoadGameLogItemNameList();// 加载游戏日志物品名
                M2Share.LoadDenyIPAddrList();// 加载IP过滤列表
                M2Share.LoadDenyAccountList();// 加载登录帐号过滤列表
                M2Share.LoadDenyChrNameList();// 加载禁止登录人物列表
                M2Share.LoadNoClearMonList();// 加载不清除怪物列表
                nCode = FrmDB.LoadItemsDB();
                if (nCode < 0)
                {
                    OutManMessage("物品数据库加载失败！！！" + "代码: " + nCode);
                    return;
                }
                else
                {
                    OutManMessage(string.Format("加载物品数据库成功[{0}]...", M2Share.UserEngine.StdItemList.Count));
                }
                nCode = FrmDB.LoadMinMap();
                if (nCode < 0)
                {
                    OutManMessage("小地图数据加载失败！！！" + "代码: " + nCode);
                    return;
                }
                else
                {
                    OutManMessage("加载小地图数据成功...");
                }
                nCode = FrmDB.LoadMapInfo();
                if (nCode < 0)
                {
                    OutManMessage("地图数据加载失败！！！" + "代码: " + nCode);
                    return;
                }
                else
                {
                    OutManMessage(string.Format("加载地图数据成功[{0}]...", M2Share.g_MapManager.m_MapList.Count));
                }
                nCode = FrmDB.LoadMonsterDB();
                if (nCode < 0)
                {
                    OutManMessage("加载怪物数据库失败！！！" + "代码: " + nCode);
                    return;
                }
                else
                {
                    OutManMessage(string.Format("加载怪物数据库成功[{0}]...", M2Share.UserEngine.MonsterList.Count));
                }
                nCode = FrmDB.LoadMagicDB();
                if (nCode < 0)
                {
                    OutManMessage("加载技能数据库失败！！！" + "代码: " + nCode);
                    return;
                }
                else
                {
                    OutManMessage(string.Format("加载技能数据库成功[{0}]...", M2Share.UserEngine.m_MagicList.Count));
                }
                nCode = FrmDB.LoadMonGen();
                if (nCode < 0)
                {
                    OutManMessage("加载怪物刷新配置信息失败！！！" + "代码: " + nCode);
                    return;
                }
                else
                {
                    OutManMessage(string.Format("加载怪物刷新配置信息成功[{0}]...", M2Share.UserEngine.m_MonGenList.Count));
                }
                if (M2Share.LoadMonSayMsg())
                {
                    OutManMessage(string.Format("加载怪物说话配置信息成功[{0}]...", M2Share.g_MonSayMsgList.Count));
                }
                M2Share.LoadDisableTakeOffList();// 加载禁止取下物品列表
                M2Share.LoadMonDropLimitList();// 加载怪物爆物品限制列表
                M2Share.LoadDisableMakeItem();// 加载禁止制造物品列表
                M2Share.LoadEnableMakeItem();// 加载可制造物品列表
                M2Share.LoadDisableMoveMap();// 加载禁止移动地图列表
                M2Share.ItemUnit.LoadCustomItemName();
                M2Share.LoadDisableSendMsgList();// 加载禁止发信息名称列表
                M2Share.LoadItemBindIPaddr();// 加载捆绑IP列表
                M2Share.LoadItemBindAccount();
                M2Share.LoadItemBindCharName();
                M2Share.LoadItemBindDieNoDropName();// 读取人物装备死亡不爆列表
                M2Share.LoadUnMasterList();// 加载出师记录表
                M2Share.LoadUnForceMasterList();// 加载强行出师记录表
                M2Share.LoadItemDblClickList();// 加载允许捡取物品
                M2Share.LoadAllowPickUpItemList();// 加载无限仓库数据
                //M2Share.g_Storage.LoadBigStorageList(GameMsgDef.g_StorageFileName);
                // OutManMessage(string.Format('加载无限仓库数据库成功[%d/%d]...', [g_Storage.HumManCount, g_Storage.RecordCount]));
                nCode = FrmDB.LoadUnbindList();
                if (nCode < 0)
                {
                    OutManMessage("加载捆装物品信息失败！！！" + "代码: " + nCode);
                    return;
                }
                else
                {
                    OutManMessage("加载捆装物品信息成功...");
                }
                M2Share.LoadBindItemTypeFromUnbindList();// 加载捆装物品类型
                nCode = FrmDB.LoadMapQuest();
                if (nCode > 0)
                {
                    OutManMessage("加载任务地图信息成功...");
                }
                else
                {
                    OutManMessage("加载任务地图信息失败！！！");
                    return;
                }
                nCode = FrmDB.LoadMapEvent();
                if (nCode < 0)
                {
                    OutManMessage("加载地图触发事件信息失败！！！");
                    return;
                }
                else
                {
                    OutManMessage("加载地图触发事件信息成功...");
                }
                nCode = FrmDB.LoadQuestDiary();
                if (nCode < 0)
                {
                    OutManMessage("加载任务说明信息失败！！！");
                    return;
                }
                else
                {
                    OutManMessage("加载任务说明信息成功...");
                }
                if (LoadAbuseInformation(".\\!abuse.txt"))
                {
                    OutManMessage("加载文字过滤信息成功...");
                }

                OutManMessage(M2Share.LoadLineNotice(M2Share.g_Config.sNoticeDir + "LineNotice.txt")
                    ? "加载公告提示信息成功..."
                    : "加载公告提示信息失败！！！");
                M2Share.LoadUserCmdList();// 加载自定义命令
                M2Share.LoadCheckItemList();// 加载禁止物品规则
                M2Share.LoadMsgFilterList();// 加载消息过滤
                M2Share.LoadShopItemList();// 加载商铺配置
                FrmDB.LoadAdminList();// 加载管理员列表
                M2Share.g_GuildManager.LoadGuildInfo();// 加载行会列表
                FrmDB.LoadBoxsList(); //加载宝箱配置
                OutManMessage("加载宝箱配置成功[" + M2Share.BoxsList.Count + "]...");
                FrmDB.LoadSuitItemList();// 读取套装装备数据
                OutManMessage("加载套装配置成功[" + M2Share.SuitItemList.Count + "]...");
                FrmDB.LoadSellOffItemList();// 读取元宝寄售列表
                OutManMessage("加载元宝寄售数据成功[" + M2Share.sSellOffItemList.Count + "]...");
                FrmDB.LoadRefineItem();
                OutManMessage("加载淬炼配置信息成功[" + M2Share.g_RefineItemList.Count + "]...");
                M2Share.g_CastleManager.LoadCastleList();
                OutManMessage("加载城堡列表成功...");
                M2Share.NoticeManager.LoadingNotice();//读取公告
                FrmDB.LoadMonFireDragonGuard();// 创建守护兽并写入列表
                M2Share.g_CastleManager.Initialize();
                OutManMessage("城堡城初始完成...");
                if ((M2Share.nServerIndex == 0))//主服务器
                {
                    M2Share.FrmSrvMsg.StartMsgServer();
                }
                else
                {
                    M2Share.FrmMsgClient.ConnectMsgServer();
                }
                StartEngine();
                M2Share.boStartReady = true;
                M2Share.g_dwRunTick = HUtil32.GetTickCount();
                M2Share.n4EBD1C = 0;
                M2Share.g_dwUsrRotCountTick = HUtil32.GetTickCount();
                GateSocket = new IServerSocket(20, Int16.MaxValue);
                GateSocket.OnClientConnect += new EventHandler<NetFramework.AsyncUserToken>(GateSocketClientConnect);
                GateSocket.OnClientDisconnect += new EventHandler<NetFramework.AsyncUserToken>(GateSocketClientDisconnect);
                //GateSocket.OnClientError += new EventHandler<NetFramework.AsyncUserToken>(GateSocketClientError);
                GateSocket.OnClientRead += new EventHandler<NetFramework.AsyncUserToken>(GateSocketClientRead);
                GateSocket.Init();
                GateSocket.Start(M2Share.g_Config.sGateAddr, M2Share.g_Config.nGatePort);
                M2Share.dwSaveDataTick = HUtil32.GetTickCount();
            }
            catch (Exception E)
            {
                OutManMessage("服务器启动异常！！！" + E.Message);
                Console.WriteLine(E.StackTrace);
            }
        }

        /// <summary>
        /// 启动引擎
        /// </summary>
        private void StartEngine()
        {
            int nCode;
            try
            {
                M2Share.FrmIDSoc.Initialize();
                OutManMessage("登录服务器连接初始化完成...");
                M2Share.g_MapManager.LoadMapDoor();
                OutManMessage("加载地图环境成功...");
                OutManMessage("正在初始化矿物数据...");
                MakeStoneMines(); // 制造矿物
                OutManMessage("矿物数据初始成功...");
                nCode = FrmDB.LoadMerchant();
                if (nCode < 0)
                {
                    OutManMessage("交易NPC列表加载失败 ！！！" + "错误码: " + nCode);
                    return;
                }
                else
                {
                    OutManMessage("加载交易NPC列表成功...");
                }

                if (!M2Share.g_Config.boVentureServer)
                {
                    nCode = FrmDB.LoadGuardList();
                    if (nCode < 0)
                    {
                        OutManMessage("守卫列表加载失败 ！！！" + "错误码: " + nCode);
                    }
                    else
                    {
                        OutManMessage("加载守卫列表成功...");
                    }
                }
                nCode = FrmDB.LoadNpcs();
                if (nCode < 0)
                {
                    OutManMessage("管理NPC列表加载失败 ！！！" + "错误码: " + nCode);
                    return;
                }
                else
                {
                    OutManMessage("加载管理NPC列表成功...");
                }
                nCode = FrmDB.LoadMakeItem();
                if (nCode < 0)
                {
                    OutManMessage("炼制物品信息加载失败 ！！！" + "错误码: " + nCode);
                    return;
                }
                else
                {
                    OutManMessage("加载炼制物品信息成功...");
                }
                nCode = FrmDB.LoadStartPoint();
                if (nCode < 0)
                {
                    OutManMessage("加载回城点配置时出现错误 ！！！(错误码: " + nCode + ")");
                    return;
                }
                else
                {
                    OutManMessage("加载回城点配置成功...");
                }
                OutManMessage("人物数据引擎启动成功...");
                M2Share.UserEngine.Initialize();
                OutManMessage("游戏处理引擎初始化成功...");
                M2Share.g_MapManager.MakeSafePkZone(); // 制造安全区光圈
                SetWindowTitle(string.Concat(M2Share.g_Config.sServerName,
                    string.Format(" [{0}]", EngineVersion.g_sVersion))); //设置程序标题
                boSaveData = true; // 保存数据;
                //SaveVariableTimer.Enabled = true;
                serverEngine.Run();
                M2Share.ThrendManage = new ThrendManage(ConnectTimerTimer,
                    new CycExecution(DateTime.Now, new TimeSpan(0, 0, 0, 0, 3000)));
                M2Share.ThrendManage.Start();
                M2Share.MainOutMessage("程序版本：" + EngineVersion.g_sVersion);
            }
            catch(Exception ex)
            {
                M2Share.MainOutMessage("服务启动时出现异常错误 ！！！");
            }
        }

        /// <summary>
        /// 制造石矿
        /// </summary>
        private void MakeStoneMines()
        {
            var mapMineList = M2Share.g_MapManager.GetMineMaps();

            foreach (var envir in mapMineList)
            {
                for (int nW = 0; nW < envir.m_nWidth; nW++)
                {
                    for (int nH = 0; nH < envir.m_nHeight; nH++)
                    {
                        new TStoneMineEvent(envir, nW, nH, M2Share.ET_STONEMINE);
                    }
                }
            }
        }

        /// <summary>
        /// 读取客户端版本信息
        /// </summary>
        /// <returns></returns>
        private bool LoadClientFile()
        {
            bool result;
            if (!(M2Share.g_Config.sClientFile1 == ""))
            {
                //M2Share.g_Config.nClientFile1_CRC = EDcodeUnit.Units.EDcodeUnit.CalcFileCRC(M2Share.g_Config.sClientFile1);
            }
            if ((M2Share.g_Config.nClientFile1_CRC != 0))
            {
                OutManMessage("加载客户端版本信息成功...");
                result = true;
            }
            else
            {
                OutManMessage("加载客户端版本信息失败！！！");
                result = true;
            }
            return result;
        }

        /// <summary>
        /// 拦截窗体关闭消息
        /// </summary>
        /// <param name="m"></param>
        //protected override void WndProc(ref Message m)
        //{
        //    const int WM_SYSCOMMAND = 0x0112;
        //    const int SC_CLOSE = 0xF060;
        //    const string sCloseServerYesNo = "是否确认关闭游戏服务器？";
        //    const string sCloseServerTitle = "确认信息";
        //    if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
        //    {
        //        if (!boServiceStarted) // 如果没有服务开始
        //        {
        //            System.Environment.Exit(System.Environment.ExitCode);
        //            return;
        //        }
        //        if (M2Share.g_boExitServer)
        //        {
        //            M2Share.boStartReady = false;
        //            return;
        //        }
        //        if (MessageBox.Show(sCloseServerYesNo, sCloseServerTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
        //        {
        //            M2Share.g_boExitServer = true;
        //            //CloseGateSocket();
        //            M2Share.g_Config.boKickAllUser = true;
        //            M2Share.ThrendManage = new ThrendManage(CloseTimerTimer, new ImmediateExecution());
        //            M2Share.ThrendManage.Start();
        //        }
        //        else
        //        {
        //            return;
        //        }
        //    }
        //    base.WndProc(ref m);
        //}

        private void CloseTimerTimer(object sender)
        {
            // FrmDB.SaveSellOffItemList;//保存元宝寄售列表
            SetWindowTitle(string.Format("{0} [正在关闭服务器({1} {2}/{3} {4})...]", M2Share.g_Config.sServerName, "人物",
                M2Share.UserEngine.OnlinePlayObject, "数据", M2Share.FrontEngine.SaveListCount()));
            if (M2Share.UserEngine.OnlinePlayObject == 0)
            {
                if (M2Share.FrontEngine.IsIdle())
                {
                    SetWindowTitle(string.Format("{0} [服务器已关闭]", M2Share.g_Config.sServerName));
                    boSaveData = false;
                    M2Share.dwSaveDataTick = HUtil32.GetTickCount() - 600000; // 1000 * 60 * 10
                    SaveItemsData();
                    StopService();
                    //this.Close();
                    M2Share.ThrendManage.Stop();
                    //Process.GetCurrentProcess().CloseMainWindow();
                }
            }
        }

        // 保存物品数据
        private void SaveItemsData()
        {
            if (HUtil32.GetTickCount() - M2Share.dwSaveDataTick > 480000) // 1000 * 60 * 8
            {
                M2Share.dwSaveDataTick = HUtil32.GetTickCount();
                if (M2Share.sSellOffItemList != null)
                {
                    FrmDB.SaveSellOffItemList();
                }
                // 保存元宝寄售数据
                //if (GameMsgDef.g_Storage != null)
                //{
                //    GameMsgDef.g_Storage.SaveToFile(GameMsgDef.g_StorageFileName);
                //}
                SaveItemNumber();
            }
        }

        private void SaveVariableTimerTimer(Object Sender)
        {
            try
            {
                SaveItemNumber();
                if (boSaveData)
                {
                    SaveItemsData();
                }
            }
            catch
            {
                M2Share.MainOutMessage("[异常] SaveVariableTimerTimer");
            }
        }

        /// <summary>
        /// 客户端连接错误
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GateSocketClientError(object sender, NetFramework.AsyncUserToken e)
        {
            //M2Share.RunSocket.CloseErrGate(e.Client.ClientSocket);
        }

        /// <summary>
        /// 断开客户连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GateSocketClientDisconnect(object sender, NetFramework.AsyncUserToken e)
        {
            M2Share.RunSocket.CloseGate(e);
        }

        /// <summary>
        /// 客户端连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GateSocketClientConnect(object sender, NetFramework.AsyncUserToken e)
        {
            M2Share.RunSocket.AddGate(e);
        }

        /// <summary>
        /// 客户端发送数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GateSocketClientRead(object sender, NetFramework.AsyncUserToken e)
        {
            M2Share.RunSocket.SocketRead(e);
        }

        /// <summary>
        /// 间隔三秒，检查DBServer和LoginSrv连接是否正常
        /// </summary>
        /// <param name="Sender"></param>
        private void ConnectTimerTimer(object Sender)
        {
            try
            {
                if (M2Share.boStartReady)
                {
                    if (!M2Share.DBEngine.DBSocket.IsConnected)//检查DBServer连接是否正常
                    {
                        M2Share.DBEngine.Connected();
                    }
                    if (!M2Share.g_Config.boIDSocketConnected) //检查LoginSrv连接是否正常
                    {
                        M2Share.FrmIDSoc.Connected();
                    }
                }
            }
            catch
            {
                M2Share.MainOutMessage("[异常] ConnectTimerTimer");
            }
        }

        private void ReloadConfig(object Sender)
        {
            try
            {
                M2Share.LoadConfig();

                //IdSrvClient.Units.IdSrvClient.FrmIDSoc.Timer1Timer(Sender);
                //if (!(M2Share.nServerIndex == 0))
                //{
                //    if (!InterMsgClient.Units.InterMsgClient.FrmMsgClient.MsgClient.Active)
                //    {
                //        InterMsgClient.Units.InterMsgClient.FrmMsgClient.MsgClient.Active = true;
                //    }
                //}
                //IdUDPClientLog.Host = M2Share.g_Config.sLogServerAddr;
                //IdUDPClientLog.Port = M2Share.g_Config.nLogServerPort;
                LoadServerTable();
                LoadClientFile();
            }
            finally
            {
            }
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        private void StartService()
        {
            M2Share.nRunTimeMax = 99999;
            M2Share.g_nSockCountMax = 0;
            M2Share.g_nUsrTimeMax = 0;
            M2Share.g_nHumCountMax = 0;
            M2Share.g_nMonTimeMax = 0;
            M2Share.g_nMonGenTimeMax = 0;
            M2Share.g_nMonProcTime = 0;
            M2Share.g_nMonProcTimeMin = 0;
            M2Share.g_nMonProcTimeMax = 0;
            M2Share.dwUsrRotCountMin = 0;
            M2Share.dwUsrRotCountMax = 0;
            M2Share.g_nProcessHumanLoopTime = 0;
            M2Share.g_dwHumLimit = 30;
            M2Share.g_dwMonLimit = 30;
            M2Share.g_dwZenLimit = 5;
            M2Share.g_dwNpcLimit = 5;
            M2Share.g_dwSocLimit = 10;
            M2Share.nDecLimit = 20;
            M2Share.g_Config.sDBSocketRecvText = "";
            M2Share.g_Config.boDBSocketWorking = false;
            M2Share.g_Config.nLoadDBErrorCount = 0;
            M2Share.g_Config.nLoadDBCount = 0;
            M2Share.g_Config.nSaveDBCount = 0;
            M2Share.g_Config.nDBQueryID = 0;
            M2Share.g_Config.nItemNumber = 0;
            M2Share.g_Config.nItemNumberEx = Int32.MaxValue / 2;
            M2Share.boStartReady = false;
            M2Share.g_boExitServer = false;
            M2Share.boFilterWord = true;
            M2Share.g_Config.nWinLotteryCount = 0;
            M2Share.g_Config.nNoWinLotteryCount = 0;
            M2Share.g_Config.nWinLotteryLevel1 = 0;
            M2Share.g_Config.nWinLotteryLevel2 = 0;
            M2Share.g_Config.nWinLotteryLevel3 = 0;
            M2Share.g_Config.nWinLotteryLevel4 = 0;
            M2Share.g_Config.nWinLotteryLevel5 = 0;
            M2Share.g_Config.nWinLotteryLevel6 = 0;
            M2Share.Initialized();
            M2Share.LoadConfig();
            M2Share.nServerIndex = 0;
            M2Share.ScriptSystem = new ScriptSystem();
            M2Share.ScriptEngine = new ScriptEngine();
            M2Share.DBEngine = new DBEngine();
            M2Share.RunSocket = new TRunSocket();
            M2Share.MainLogMsgList = new TStringList();
            M2Share.LogStringList = new TStringList();
            M2Share.LogonCostLogList = new TStringList();
            M2Share.g_MapManager = new MapManager();
            M2Share.ActorsSystem = new ObjectSystem();
            M2Share.CommandSystem = new CommandManager();
            M2Share.ItemUnit = new TItemUnit();
            M2Share.MagicManager = new MagicManager();
            M2Share.NoticeManager = new TNoticeManager();
            M2Share.g_GuildManager = new TGuildManager();
            M2Share.g_EventManager = new TEventManager();
            M2Share.g_CastleManager = new TCastleManager();
            M2Share.FrontEngine = new TFrontEngine(true);
            M2Share.UserEngine = new TUserEngine();
            M2Share.FrmIDSoc = new TFrmIDSoc();
            M2Share.FrmMsgClient = new TFrmMsgClient();
            M2Share.FrmSrvMsg = new TFrmSrvMsg();
            M2Share.RobotManage = new TRobotManage();
            M2Share.g_MakeItemList = new TStringList();
            M2Share.g_RefineItemList = new List<TRefineItemInfo>();// 淬炼配置列表
            M2Share.g_StartPointList = new List<TStartPoint>();
            M2Share.ServerTableList = new List<TStringList>();
            M2Share.g_DenySayMsgList = new IList<string, uint>();
            M2Share.MiniMapList = new List<TMinMapInfo>();
            M2Share.g_UnbindList = new List<TUnbindInfo>();//解包物品列表
            M2Share.LineNoticeList = new TStringList();
            M2Share.g_UserCmdList = new Dictionary<string, int>();// 自定义命令列表
            M2Share.g_CheckItemList = new List<TCheckItem>();// 禁止物品规则
            M2Share.g_MsgFilterList = new List<TFilterMsg>();// 消息过滤规则
            M2Share.g_ShopItemList = new List<TShopItem>();// 商铺物品列表
            M2Share.QuestDiaryList = new List<TQDDinfo>();
            M2Share.BoxsList = new List<TBoxsInfo>();//  宝箱
            M2Share.SuitItemList = new List<TSuitItem>();//  套装
            M2Share.sSellOffItemList = new List<TDealOffInfo>();// 元宝寄售列表
            M2Share.ItemEventList = new TStringList();
            M2Share.AbuseTextList = new TStringList();
            M2Share.g_MonSayMsgList = new TStringList();
            M2Share.g_DisableMakeItemList = new TStringList();
            M2Share.g_EnableMakeItemList = new TStringList();
            M2Share.g_DisableMoveMapList = new TStringList();
            M2Share.g_ItemNameList = new TStringList();
            M2Share.g_DisableSendMsgList = new TStringList();
            M2Share.g_MonDropLimitLIst = new List<TMonDrop>();
            M2Share.g_DisableTakeOffList = new TStringList();
            M2Share.g_UnMasterList = new TStringList();
            M2Share.g_UnForceMasterList = new TStringList();
            M2Share.g_GameLogItemNameList = new TStringList();
            M2Share.g_DenyIPAddrList = new TStringList();
            M2Share.g_DenyChrNameList = new TStringList();
            M2Share.g_DenyAccountList = new TStringList();
            M2Share.g_NoClearMonList = new TStringList();
            M2Share.g_ItemBindIPaddr = new List<TItemBind>();
            M2Share.g_ItemBindAccount = new List<TItemBind>();
            M2Share.g_ItemBindCharName = new List<TItemBind>();// 物品人物绑定表(对应的玩家才能戴物品
            M2Share.g_ItemBindDieNoDropName = new List<TItemBind>();// 人物装备死亡不爆列表
            // GameMsgDef.g_Storage = new TStorage();
            M2Share.g_MapEventListOfDropItem = new List<TMapEvent>();
            M2Share.g_MapEventListOfPickUpItem = new List<TMapEvent>();
            M2Share.g_MapEventListOfMine = new List<TMapEvent>();
            M2Share.g_MapEventListOfWalk = new List<TMapEvent>();
            M2Share.g_MapEventListOfRun = new List<TMapEvent>();
            M2Share.LogMsgCriticalSection = new object();
            M2Share.ProcessMsgCriticalSection = new object();
            M2Share.ProcessHumanCriticalSection = new object();
            M2Share.HumanSortCriticalSection = new object();
            M2Share.g_Config.UserIDSection = new object();
            M2Share.UserDBSection = new object();
            M2Share.g_DynamicVarList = new List<TDynamicVar>();
            if (!Directory.Exists(M2Share.g_Config.sLogDir))
            {
                Directory.CreateDirectory(M2Share.g_Config.sLogDir);
            }
            M2Share.nShiftUsrDataNameNo = 1;
            OutManMessage("正在读取配置信息...");
            M2Share.DBEngine.DBSocket.Address = M2Share.g_Config.sDBAddr;
            M2Share.DBEngine.DBSocket.Port = M2Share.g_Config.nDBPort;
            M2Share.DBEngine.Start();
            SetWindowTitle(M2Share.g_Config.sServerName);
            //LoadServerTable();
            //IdUDPClientLog.Host = M2Share.g_Config.sLogServerAddr;
            //IdUDPClientLog.Port = M2Share.g_Config.nLogServerPort;
            M2Share.g_dwStartTick = HUtil32.GetTickCount();
            M2Share.dwSaveDataTick = HUtil32.GetTickCount() + 300000;// 1000 * 60 * 5
            M2Share.g_StorageFileName = M2Share.g_Config.sEnvirDir + "\\Market_Storage\\";
            if (!Directory.Exists(M2Share.g_StorageFileName))
            {
                Directory.CreateDirectory(M2Share.g_StorageFileName);
            }
            M2Share.g_StorageFileName = M2Share.g_StorageFileName + "UserStorage.db";
            M2Share.ThrendManage = new ThrendManage(RefreshData, new CycExecution(DateTime.Now, new TimeSpan(0, 0, 0, 0, 2000)));
            M2Share.ThrendManage.Start();
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        private void StopService()
        {
            TGameConfig Config;
            try
            {
                Config = M2Share.g_Config;
                GateSocket.Shutdown();
                SaveItemNumber();// 保存系统变量
                M2Share.MainLogMsgList = null;
                M2Share.LogStringList = null;
                M2Share.LogonCostLogList = null;
                M2Share.g_EventManager = null;
                M2Share.ServerTableList = null;
                M2Share.g_DenySayMsgList = null;
                M2Share.MiniMapList = null;
                M2Share.g_UnbindList = null;
                M2Share.LineNoticeList = null;
                M2Share.g_UserCmdList = null;// 自定义命令列表
                M2Share.QuestDiaryList = null;
                if (M2Share.g_CheckItemList.Count > 0)
                {
                    for (var i = 0; i < M2Share.g_CheckItemList.Count; i++)// 禁止物品规则
                    {
                        if (M2Share.g_CheckItemList[i] != null)
                        {
                            //Dispose(M2Share.g_CheckItemList[i]);
                        }
                    }
                }
                M2Share.g_CheckItemList = null;
                if (M2Share.g_MsgFilterList.Count > 0)// 消息过滤规则
                {
                    for (var i = 0; i < M2Share.g_MsgFilterList.Count; i++)
                    {
                        if (((TFilterMsg)(M2Share.g_MsgFilterList[i])) != null)
                        {
                            //this.Dispose(((TFilterMsg)(M2Share.g_MsgFilterList[i])));
                        }
                    }
                }
                M2Share.g_MsgFilterList = null;
                unsafe
                {
                    //if (M2Share.g_ShopItemList.Count > 0) // 商铺物品列表
                    //{
                    //    for (var i = 0; i < M2Share.g_ShopItemList.Count; i++)
                    //    {
                    //        if (M2Share.g_ShopItemList[i] != null)
                    //        {
                    //           //Marshal.FreeHGlobal((IntPtr)M2Share.g_ShopItemList[i]);
                    //        }
                    //    }
                    //}
                }
                M2Share.g_ShopItemList = null;
                if (M2Share.BoxsList.Count > 0)// 宝箱
                {
                    for (var i = 0; i < M2Share.BoxsList.Count; i++)
                    {
                        //if (((TBoxsInfo*)(M2Share.BoxsList[i])) != null)
                        //{
                        //    this.Dispose(((TBoxsInfo*)(M2Share.BoxsList[i])));
                        //}
                    }
                }
                M2Share.BoxsList = null;
                if (M2Share.SuitItemList.Count > 0) //套装
                {
                    for (var i = 0; i < M2Share.SuitItemList.Count; i++)
                    {
                        //if (((TSuitItem)(M2Share.SuitItemList[i])) != null)
                        //{
                        //    this.Dispose(((TSuitItem)(M2Share.SuitItemList[i])));
                        //}
                    }
                }
                M2Share.SuitItemList = null;// 元宝寄售列表
                if (M2Share.sSellOffItemList.Count > 0)
                {
                    //for (var i = 0; i < M2Share.sSellOffItemList.Count; i++)
                    //{
                    //    if (((TDealOffInfo)(M2Share.sSellOffItemList[i])) != null)
                    //    {
                    //        this.Dispose(((TDealOffInfo)(M2Share.sSellOffItemList[i])));
                    //    }
                    //}
                }
                M2Share.sSellOffItemList = null;// 元宝寄售列表
                M2Share.ItemEventList = null;
                M2Share.AbuseTextList = null;
                M2Share.g_HighMCHuman = null;
                M2Share.g_DisableMakeItemList = null;
                M2Share.g_EnableMakeItemList = null;
                M2Share.g_DisableMoveMapList = null;
                M2Share.g_ItemNameList = null;
                M2Share.g_DisableSendMsgList = null;
                M2Share.g_MonDropLimitLIst = null;
                M2Share.g_DisableTakeOffList = null;
                M2Share.g_UnMasterList = null;
                M2Share.g_UnForceMasterList = null;
                M2Share.g_GameLogItemNameList = null;
                M2Share.g_DenyIPAddrList = null;
                M2Share.g_DenyChrNameList = null;
                M2Share.g_DenyAccountList = null;
                M2Share.g_NoClearMonList = null;

                //GameMsgDef.g_Storage.UnLoadBigStorageList();
                //GameMsgDef.g_Storage.Free;
                if (M2Share.g_ItemBindIPaddr.Count > 0)
                {
                    for (var i = 0; i < M2Share.g_ItemBindIPaddr.Count; i++)
                    {
                        //if (((TItemBind)(M2Share.g_ItemBindIPaddr[i])) != null)
                        //{
                        //    this.Dispose(((TItemBind)(M2Share.g_ItemBindIPaddr[i])));
                        //}
                    }
                }
                if (M2Share.g_ItemBindAccount.Count > 0)
                {
                    for (var i = 0; i < M2Share.g_ItemBindAccount.Count; i++)
                    {
                        //if (((TItemBind)(M2Share.g_ItemBindAccount[i])) != null)
                        //{
                        //    this.Dispose(((TItemBind)(M2Share.g_ItemBindAccount[i])));
                        //}
                    }
                }
                if (M2Share.g_ItemBindCharName.Count > 0)
                {
                    for (var i = 0; i < M2Share.g_ItemBindCharName.Count; i++)
                    {
                        //if (((TItemBind)(M2Share.g_ItemBindCharName[i])) != null)
                        //{
                        //  this.Dispose(((TItemBind)(M2Share.g_ItemBindCharName[i])));
                        //}
                    }
                }
                M2Share.g_ItemBindIPaddr = null;
                M2Share.g_ItemBindAccount = null;
                M2Share.g_ItemBindCharName = null;
                if (M2Share.g_ItemBindDieNoDropName.Count > 0)
                {
                    for (var i = 0; i < M2Share.g_ItemBindDieNoDropName.Count; i++)
                    {
                        //if (((TItemBind)(M2Share.g_ItemBindDieNoDropName[i])) != null)
                        //{
                        //    this.Dispose(((TItemBind)(M2Share.g_ItemBindDieNoDropName[i])));
                        //}
                    }
                }
                M2Share.g_ItemBindDieNoDropName = null;
                if (M2Share.g_MapEventListOfDropItem.Count > 0)
                {
                    for (var i = 0; i < M2Share.g_MapEventListOfDropItem.Count; i++)
                    {
                        //if (((TMapEvent)(M2Share.g_MapEventListOfDropItem[i])) != null)
                        //{
                        //    this.Dispose(((TMapEvent)(M2Share.g_MapEventListOfDropItem[i])));
                        //}
                    }
                }
                M2Share.g_MapEventListOfDropItem = null;
                if (M2Share.g_MapEventListOfPickUpItem.Count > 0)
                {
                    for (var i = 0; i < M2Share.g_MapEventListOfPickUpItem.Count; i++)
                    {
                        //if (((TMapEvent)(M2Share.g_MapEventListOfPickUpItem[i])) != null)
                        //{
                        //    this.Dispose(((TMapEvent)(M2Share.g_MapEventListOfPickUpItem[i])));
                        //}
                    }
                }
                M2Share.g_MapEventListOfPickUpItem = null;
                if (M2Share.g_MapEventListOfMine.Count > 0)
                {
                    for (var i = 0; i < M2Share.g_MapEventListOfMine.Count; i++)
                    {
                        //if (((TMapEvent)(M2Share.g_MapEventListOfMine[i])) != null)
                        //{
                        //    this.Dispose(((TMapEvent)(M2Share.g_MapEventListOfMine[i])));
                        //}
                    }
                }
                M2Share.g_MapEventListOfMine = null;
                if (M2Share.g_MapEventListOfWalk.Count > 0)
                {
                    for (var i = 0; i < M2Share.g_MapEventListOfWalk.Count; i++)
                    {
                        //if (((TMapEvent)(M2Share.g_MapEventListOfWalk[i])) != null)
                        //{
                        //    this.Dispose(((TMapEvent)(M2Share.g_MapEventListOfWalk[i])));
                        //}
                    }
                }
                M2Share.g_MapEventListOfWalk = null;
                if (M2Share.g_MapEventListOfRun.Count > 0)
                {
                    for (var i = 0; i < M2Share.g_MapEventListOfRun.Count; i++)
                    {
                        //if (((TMapEvent)(M2Share.g_MapEventListOfRun[i])) != null)
                        //{
                        //    this.Dispose(((TMapEvent)(M2Share.g_MapEventListOfRun[i])));
                        //}
                    }
                }
                M2Share.g_MapEventListOfRun = null;
                if (M2Share.g_DynamicVarList.Count > 0)
                {
                    for (var i = 0; i < M2Share.g_DynamicVarList.Count; i++)
                    {
                        if (((TDynamicVar)(M2Share.g_DynamicVarList[i])) != null)
                        {
                            // this.Dispose(((TDynamicVar)(M2Share.g_DynamicVarList[i])));
                        }
                    }
                }
                M2Share.g_DynamicVarList = null;
                if (M2Share.g_BindItemTypeList != null)
                {
                    if (M2Share.g_BindItemTypeList.Count > 0)
                    {
                        for (var i = 0; i < M2Share.g_BindItemTypeList.Count; i++)
                        {
                            //if (((TBindItem)(M2Share.g_BindItemTypeList[i])) != null)
                            //{
                            //    this.Dispose(((TBindItem)(M2Share.g_BindItemTypeList[i])));
                            //}
                        }
                    }
                    M2Share.g_BindItemTypeList = null;
                }
                M2Share.g_AllowPickUpItemList = null;
                if (M2Share.g_ItemDblClickList.Count > 0)
                {
                    for (var i = 0; i < M2Share.g_ItemDblClickList.Count; i++)
                    {
                        //if (((TItemEvent)(M2Share.g_ItemDblClickList[i])) != null)
                        //{
                        //    this.Dispose(((TItemEvent)(M2Share.g_ItemDblClickList[i])));
                        //}
                    }
                }
                M2Share.g_ItemDblClickList = null;
                if (M2Share.g_StartPointList.Count > 0)
                {
                    for (var i = 0; i < M2Share.g_StartPointList.Count; i++)
                    {
                        //if (((TStartPoint)(M2Share.g_StartPointList[i])) != null)
                        //{
                        //    this.Dispose(((TStartPoint)(M2Share.g_StartPointList.Values[i])));
                        //}
                    }
                }
                M2Share.g_StartPointList = null;
                if (M2Share.g_MakeItemList.Count > 0)
                {
                    for (var i = 0; i < M2Share.g_MakeItemList.Count; i++)
                    {
                        //((M2Share.g_MakeItemList.Values[i]) as List<string>).Free;
                    }
                }
                M2Share.g_MakeItemList = null;
                if (M2Share.g_RefineItemList.Count > 0)
                {
                    for (var i = 0; i < M2Share.g_RefineItemList.Count; i++)
                    {
                        //if (((M2Share.g_RefineItemList.Values[i]) as ArrayList).Count > 0)
                        //{
                        //    for (K = 0; K < ((M2Share.g_RefineItemList.Values[i]) as ArrayList).Count; K ++ )
                        //    {
                        //        if (((TRefineItemInfo)(((M2Share.g_RefineItemList.Values[i]) as ArrayList)[K])) != null)
                        //        {
                        //            this.Dispose(((TRefineItemInfo)(((M2Share.g_RefineItemList.Values[i]) as ArrayList)[K])));
                        //        }
                        //    }
                        //}
                        // ((M2Share.g_RefineItemList.Values[i]) as ArrayList).Free;
                    }
                }
                M2Share.g_RefineItemList = null;
            }
            catch
            {
            }
        }

        /// <summary>
        /// 输出引擎信息
        /// </summary>
        /// <param name="nMsg"></param>
        private void OutManMessage(string nMsg)
        {
            Console.WriteLine(nMsg);
        }
    }
}